package com.zen.lon.open.remote.spi;

import com.zen.lon.open.remote.exp.RemoteClientException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
import org.springframework.core.Ordered;

/**
 * jdk spi 工具类
 *
 * @author ZonLen since on 2021/7/6 下午9:34
 */
public class ServiceBootstrap {

  public static <S> S loadFirst(Class<S> clazz) {
    Iterator<S> iterator = loadAll(clazz);
    if (!iterator.hasNext()) {
      throw new RemoteClientException(String.format(
          "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
          clazz.getName()));
    }
    return iterator.next();
  }

  public static <S> Iterator<S> loadAll(Class<S> clazz) {
    ServiceLoader<S> loader = ServiceLoader.load(clazz);

    return loader.iterator();
  }

  public static <S extends Ordered> List<S> loadAllOrdered(Class<S> clazz) {
    Iterator<S> iterator = loadAll(clazz);

    if (!iterator.hasNext()) {
      throw new RemoteClientException(String.format(
          "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
          clazz.getName()));
    }
    final List<S> candidates = new ArrayList<>();
    while (iterator.hasNext()) {
      candidates.add(iterator.next());
    }
    candidates.sort(Comparator.comparingInt(Ordered::getOrder));
    return candidates;
  }

  public static <S extends Ordered> S loadPrimary(Class<S> clazz) {
    List<S> candidates = loadAllOrdered(clazz);
    return candidates.get(0);
  }

  public static <S> S loadOneByClazz(Class<S> clazz, Class<? extends S> subClazz) {
    final Iterator<S> iterator = loadAll(clazz);
    while (iterator.hasNext()) {
      final S next = iterator.next();
      if (next.getClass() == subClazz) {
        return next;
      }
    }
    return null;
  }
}
